<?php

namespace App\Http\Controllers\Admin;

use App\Classes\UploadImg;
use App\Http\Controllers\AdminController;
use App\Jobs\SetAdminLog;
use App\Models\MemberGroup;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

use App\Http\Requests;

class MemberController extends AdminController
{
    /**
     * 验证条件数组
     * @var array
     */
    protected $verifyFactor = [
        'groupID'       => 'required',
        'name'          => 'required|unique:users',
        'password'      => 'required|confirmed|min:6'
    ];

    public function getIndex(Request $request)
    {
        //获取会员列表
        $members = User::where('type', 'member');
        //分组筛选
        if($request->has('groupID'))
        {
            $members->where('groupID', $request->input('groupID'));
        }
        //时间筛选
        if($request->has('time'))
        {
            $time = explode(' - ',$request->input('time'));
            if(isset($time[0]) && isset($time[1]))
            {
                $startime = $time[0];
                $endtime = $time[1];
                $members->where('updated_at','>=',$startime)->where('updated_at','<=',$endtime);
            }
        }
        //搜索
        if($request->has('searchType') && $request->has('keyword'))
        {
            switch ($request->input('searchType'))
            {
                case 'id':
                    $members->where('id',$request->input('keyword'));
                    break;
                case 'email':
                case 'name':
                case 'realName':
                    $members->where($request->input('searchType'), 'LIKE', '%'.$request->input('keyword').'%');
                    break;
            }
        }
        $members = $members ->orderBy('id', 'desc')->paginate(20);
        //获取会员分组
        $memberGroup = MemberGroup::all()->keyBy('id');

        return view('admin.member')->with(['members' => $members, 'memberGroup' => $memberGroup]);
    }

    /**
     * 添加会员
     * @return $this
     */
    public function getAdd()
    {
        //获取会员分组
        $memberGroup = MemberGroup::all()->keyBy('id');

        return view('admin.member-add')->with(['memberGroup' => $memberGroup]);
    }
    public function postAdd(Request $request)
    {
        //验证
        $verifyMsg = $this->verification($request->input(), $request->has('email') ? ['email' => 'email|max:255|unique:users'] : []);
        if ($verifyMsg)
        {
            return redirect()->action('Admin\MemberController@getAdd')->withInput()->withErrors($verifyMsg);
        }
        //分解分组
        $explode = explode('-',$request->input('groupID'));
        //越级操作
        if ($explode[0] == 'system')
        {
            if ($this->verifyIllegality($request->group[$request->input('groupID')]->lv))
                return ShowMsg('error', getLang('Tips', 'illegal'), action('Admin\AuthController@getLogout'), 3);
        } elseif ($explode[0] == 'member') {
            $lv = MemberGroup::where('id', $explode[1])->pluck('lv');
        }
        //整理数据
        $request->merge([
            'type'          =>  $explode[0],
            'lv'            =>  $explode[0] == 'system' ? $request->group[$explode[1]]->lv : $lv,
            'groupID'       =>  $explode[1],
            'thumb'         =>  config('imgUpdate.memberDefault'),
            'verify'        =>  1,
            'verifyTime'    =>  Carbon::create(),
            'password'      =>  bcrypt($request->input('password'))
        ]);
        //Create
        if (User::create($request->input()))
        {
            //setLog
            $this->setLog('create', NULL, json_encode($request->except('_token')));
            return ShowMsg('success', getLang('Tips', 'createSuccess'), action('Admin\MemberController@getIndex'), 1);
        }

        return ShowMsg('error', getLang('Tips', 'createFail'), action('Admin\MemberController@getIndex'), 1);
    }

    /**
     * 修改
     * @param $id
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function getEdit($id)
    {
        $members = User::find($id);
        if (empty($members))
            return redirect()->back();
        if($members->type == 'system')
        {
            if ($this->verifyIllegality($members->lv))
                return ShowMsg('error', getLang('Tips', 'illegal'), action('Admin\AuthController@getLogout'), 3);
        }
        $thumb = parse_url($members->thumb);
        if($thumb['scheme'] == 'http' || $thumb['scheme'] == 'https')
        {
        }else{
            $members->thumb = action('ImgController@getMember', ['uid' => $members->id, 'sourceName' => $members->thumb, 'size' => '160x160']);
        }
        //获取会员分组
        $memberGroup = MemberGroup::all()->keyBy('id');

        return view('admin.member-edit')->with(['members' => $members, 'memberGroup' => $memberGroup]);
    }
    public function postEdit(Request $request, $id)
    {
        //验证
        $verifyMsg = $this->verification(
            $request->input('password') ? $request->input() : $request->except('password'),
            $request->has('email') ? ['email' => 'email|max:255|unique:users,email,'.$id] : []
        );
        if ($verifyMsg)
        {
            return redirect()->action('Admin\MemberController@getEdit', ['id' => $id])->withErrors($verifyMsg);
        }
        //分解分组
        $explode = explode('-',$request->input('groupID'));
        //整理数据
        if ($explode[0] == 'member')
            $lv = MemberGroup::where('id', $explode[1])->pluck('lv');
        $request->merge(['lv' => $explode[0] == 'system' ? $request->group[$explode[1]]->lv : $lv,
            'type'      =>  $explode[0],
            'groupID'   =>  $explode[1]
        ]);
        if ($request->input('password'))
            $request->merge(['password' => bcrypt($request->input('password'))]);

        //修改前的值
        $origin = User::find($id)->toArray();
        //Update
        if (User::where('id', $id)->update($request->input('password') ? $request->except('_token', 'password_confirmation') : $request->except(['_token', 'password', 'password_confirmation'])))
        {
            //setLog
            $this->setLog('update', json_encode($origin), json_encode($request->except('_token')));
            return ShowMsg('success', getLang('Tips', 'updateSuccess'), action('Admin\MemberController@getEdit', ['id' => $id]), 1);
        }
        return ShowMsg('error', getLang('Tips', 'updateFail'), action('Admin\MemberController@getEdit', ['id' => $id]), 1);
    }

    /**
     * 删除
     * @param $id
     * @return $this
     */
    public function getDel($id)
    {
        if ((int)$id === 1)
            return ShowMsg('error', getLang('Tips', 'userNotDelete'),'',1);
        //获取用户
        $user = User::find($id);
        $origin = $user->toArray();
        if (!empty($user))
        {
            if ($user->type == 'system')
            {
                if ($this->verifyIllegality($user->lv))
                    return ShowMsg('error', getLang('Tips', 'illegal'), action('Admin\AuthController@getLogout'), 1);
            }
            if ($user->delete())
            {
                //setLog
                $this->setLog('delete', json_encode($origin));
                return ShowMsg('success', getLang('Tips', 'deleteSuccess'),'',1);
            }
        }
        return ShowMsg('error', getLang('Tips', 'illegal'),'',1);
    }

    /**
     * 上传头像
     * @param UploadImg $uploadImg
     * @param Request $request
     */
    public function postUpload(UploadImg $uploadImg, Request $request)
    {
        if ($request->hasFile('avatar_file'))
        {
            if ($request->file('avatar_file')->isValid())
            {
                $avatar_file = $request->file('avatar_file');
                $avatar_data = $request->input('avatar_data');
                $avatar_data_obj = json_decode(stripslashes($avatar_data));
                $uploadImg->savePath = config('imgUpdate.memberPath').$request->input('id').'/';
                //横纵比例
                $prefix = md5(time());
                $aspectRatio = [
                    [
                        'width'     =>  $avatar_data_obj->width,
                        'height'    =>  $avatar_data_obj->height,
                        'path'      =>  $prefix.'.png'
                    ]
                ];
                $backData = $uploadImg->upThumb($avatar_file, $avatar_data, $aspectRatio);
                if(count($backData) > 0)
                {
                    $origin = User::where('id', $request->input('id'))->first();
                    //更新数据
                    $check = User::where('id', $request->input('id'))->update(['thumb' => $backData['thumb']]);
                    if($check)
                    {
                        //setLog
                        $this->setLog('updateThumb', json_encode($origin), json_encode($backData));
                        $backData['msg'] = '更新成功';
                    }else{
                        $backData['msg'] = '更新失败';
                    }
                    //返回数据
                    echo json_encode($backData);
                }
            }
        }
    }

    /**
     * 验证是否越级操作
     * @param $lv
     * @return bool
     */
    private function verifyIllegality($lv)
    {
        if ($this->user->id != 1 && $this->user->lv >= $lv)
            return true;
        return false;
    }

    /**
     * 记录日志
     * @param string$type 类型 create update delete
     * @param json null $origin 事件发生前
     * @param json null $ending 事件发生后
     */
    private function setLog($type, $origin = NULL, $ending = NULL)
    {
        switch ($type)
        {
            case 'create':
                $event = [
                    'msg'   =>  'member.create',
                    'type'  =>  'Create'
                ];
                break;
            case 'update':
                $event = [
                    'msg'   =>  'member.update',
                    'type'  =>  'Update'
                ];
                break;
            case 'delete':
                $event = [
                    'msg'   =>  'member.delete',
                    'type'  =>  'Delete'
                ];
                break;
            case 'updateThumb':
                $event = [
                    'msg'   =>  'member.updateThumb',
                    'type'  =>  'Update'
                ];
                break;
        }
        //push to queue
        $geoIP = geoip()->getLocation();
        $this->dispatch(new SetAdminLog($this->user->id, $geoIP, $event['msg'], Carbon::now(), $event['type'], $origin, $ending));
    }
}
